"""
@author: yinjx
@file: lianxi-facing-sanleshopping.py
@time: 2023/4/13 15:56
"""
# 面向对象实现三乐系统
# 实例属性：商品信息 系统说明信息 当前多个用户
# 方法：登录 注册  查看商品  添加购物车 结算

# 设定用户类
# 实例属性：名字 密码  钱  每个用户的购物车
# 方法：

import json
class User():
    def __init__(self,name,passwd,initial_amout):
        self.name = name
        self.passwd = passwd
        self.initial_amout = initial_amout
        self.shopping_car = {}


class ShoppingSystem:
    def __init__(self, goods_info, sys_info):
        self.goods_info = goods_info
        self.sys_info = sys_info
        self.userdict = {}

    def register(self,name,passwd,initial_amout):
        #创建一个新用户 实例化User类
        if name not in self.userdict:
            user = User(name, passwd, initial_amout)
            #把名字作为key,user对象作为value存在self.userdict里面
            self.userdict[name] = user
            userdict_str = json.dumps(self.userdict)  # 将字典转化为字符串
            fp = open("userinfo1.txt", "w")
            fp.write(userdict_str)

        else:
            print("用户已存在")
    def login(self,name,passwd):
        fp = open("userinfo1.txt")
        read_str = fp.read()
        fp.close()
        self.userdict = json.loads(read_str)
        if name in self.userdict and passwd == self.userdict[name]['passwd']:
            print("登录成功")
        else:
            print("登录失败")

fruit_goods = {
    'f0001':{"name": "苹果", "price": 8},
    'f0002':{"name": "香蕉", "price": 4}
}
medicine_goods ={
    'm00001':{"name": "奥司他韦","price":65},
    'm00002':{"name": "阿司匹林","price":20}
}
system1 = ShoppingSystem(fruit_goods, "水果购物系统")
system2 = ShoppingSystem(medicine_goods, "药品购物系统")
#print(system1.goods_info)#里面的相当于存储了一个实例，可以通过实例的属性获到它的信息
system = [system1, system2]
while 1:
    print("当前购物系统有： ")
    for k,v in enumerate(system):
        print(f"{k}.{v.sys_info}")
    c1 = input("请输入你的选择（按q退出）")
    if c1 == "q":
        break
    if c1.isdigit() and int(c1) < len(system):
        c1 = int(c1)
        current_system=system[c1]
        print(f"欢迎进入{current_system.sys_info}".center(40,"*"))
        while 1:
            c2 = input("1.登录\n2.注册\n请输入你的选择（按q退出)")
            if c2 == "q":
                break
            if c2 == "1":
                name, passwd = input("请输入你的名字 密码 ").split()
                current_system.login(name, passwd)

                pass
            elif c2 == "2":
                name,passwd,amout = input("请输入你的名字 密码 初试金额（使用空白分割").split()
                current_system.register(name, passwd, amout)
                pass
            else:
                print("输入有误")

    else:
        print("输入有误 请重新输入")




